<template>
  <div class="home">
    <header>
      <nav class="header-container">
        <h1 class="header-title">学习</h1>
        <form class="search-form" @submit.prevent="handleSearch">
          <input
              type="text"
              class="search-input"
              placeholder="搜索文章"
              v-model="searchKeyword"
          />
          <button class="search-button" type="submit">搜索</button>
        </form>
      </nav>
    </header>
    <van-tabs v-model="activeTab" @change="onTabChange">
      <van-tab title="综合" name="all">
        <div class="card-container">
          <router-link v-for="(item, index) in list0" :key="index" :to="'/articleDetails/' + item.articleId" tag="div" class="card">
            <div class="card-header">
    <span class="author">
      <router-link :to="{ path: '/personalHomeCopy/'+item.userId }">
        <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
      </router-link>
      {{ item.authorUsername }} | {{ item.createdAt }}
    </span>
              <span class="view-count">
      <van-icon name="good-job-o"/> {{ item.goods }} |
      <van-icon name="eye-o"/> {{ item.views }} |
      <van-icon name="comment-o"/> {{ item.commentsCount }}
    </span>
            </div>
            <div class="card-content">
              <img :src="item.image" alt="" class="image"/>
              <h5>{{ item.title }}</h5>
              <p v-if="!detailVisible && activeIndex === index">{{ item.content.slice(0, 100) + '...' }}</p>
              <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
            </div>
          </router-link>
        </div>
      </van-tab>
      <van-tab title="备考经验" name="bkjy">
        <div class="card-container">
          <router-link v-for="(item, index) in list0" :key="index" :to="'/articleDetails/' + item.articleId" tag="div"
                       class="card">
            <div class="card-header">
                <span class="author">
                  <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
                  {{ item.authorUsername }} | {{ item.createdAt }}
                </span>
              <span class="view-count"><van-icon name="good-job-o"/>{{ item.goods }}|<van-icon
                  name="eye-o"/>{{ item.views }}  | <van-icon name="comment-o"/>{{ item.commentsCount }} </span>
            </div>
            <div class="card-content">
              <img :src="item.image" alt="" class="image"/>
              <h5>{{ item.title }}</h5>
              <p v-if="!detailVisible && activeIndex === index">{{ item.content.slice(0, 100) + '...' }}</p>
              <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
            </div>
          </router-link>
        </div>
      </van-tab>
      <van-tab title="案例分析" name="alfx">
        <div class="card-container">
          <router-link v-for="(item, index) in list0" :key="index" :to="'/articleDetails/' + item.articleId" tag="div"
                       class="card">
            <div class="card-header">
                <span class="author">
                  <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
                  {{ item.authorUsername }} | {{ item.createdAt }}
                </span>
              <span class="view-count"><van-icon name="good-job-o"/>{{ item.goods }}|<van-icon
                  name="eye-o"/>{{ item.views }}  | <van-icon name="comment-o"/>{{ item.commentsCount }} </span>
            </div>
            <div class="card-content">
              <img :src="item.image" alt="" class="image"/>
              <h5>{{ item.title }}</h5>
              <p v-if="!detailVisible && activeIndex === index">{{ item.content.slice(0, 100) + '...' }}</p>
              <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
            </div>
          </router-link>
        </div>
      </van-tab>
      <van-tab title="快题" name="kt">
        <div class="card-container">
          <router-link v-for="(item, index) in list0" :key="index" :to="'/articleDetails/' + item.articleId" tag="div"
                       class="card">
            <div class="card-header">
                <span class="author">
                  <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
                  {{ item.authorUsername }} | {{ item.createdAt }}
                </span>
              <span class="view-count"><van-icon name="good-job-o"/>{{ item.goods }}|<van-icon
                  name="eye-o"/>{{ item.views }}  | <van-icon name="comment-o"/>{{ item.commentsCount }} </span>
            </div>
            <div class="card-content">
              <img :src="item.image" alt="" class="image"/>
              <h5>{{ item.title }}</h5>
              <p v-if="!detailVisible && activeIndex === index">{{ item.content.slice(0, 100) + '...' }}</p>
              <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
            </div>
          </router-link>
        </div>
      </van-tab>
      <van-tab title="建筑史" name="jzs">
        <div class="card-container">
          <router-link v-for="(item, index) in list0" :key="index" :to="'/articleDetails/' + item.articleId" tag="div"
                       class="card">
            <div class="card-header">
                <span class="author">
                  <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
                  {{ item.authorUsername }} | {{ item.createdAt }}
                </span>
              <span class="view-count"><van-icon name="good-job-o"/>{{ item.goods }}|<van-icon
                  name="eye-o"/>{{ item.views }}  | <van-icon name="comment-o"/>{{ item.commentsCount }} </span>
            </div>
            <div class="card-content">
              <img :src="item.image" alt="" class="image"/>
              <h5>{{ item.title }}</h5>
              <p v-if="!detailVisible && activeIndex === index">{{ item.content.slice(0, 100) + '...' }}</p>
              <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
            </div>
          </router-link>
        </div>
      </van-tab>
      <van-tab title="技术" name="js">
        <div class="card-container">
          <router-link v-for="(item, index) in list0" :key="index" :to="'/articleDetails/' + item.articleId" tag="div"
                       class="card">
            <div class="card-header">
                <span class="author">
                  <img v-if="item.authorImageUrl" :src="item.authorImageUrl" alt="Author Avatar" class="card__avatar"/>
                  {{ item.authorUsername }} | {{ item.createdAt }}
                </span>
              <span class="view-count"><van-icon name="good-job-o"/>{{ item.goods }}|<van-icon
                  name="eye-o"/>{{ item.views }}  | <van-icon name="comment-o"/>{{ item.commentsCount }} </span>
            </div>
            <div class="card-content">
              <img :src="item.image" alt="" class="image"/>
              <h5>{{ item.title }}</h5>
              <p v-if="!detailVisible && activeIndex === index">{{ item.content.slice(0, 100) + '...' }}</p>
              <p v-if="detailVisible && activeIndex === index">{{ item.content }}</p>
            </div>
          </router-link>
        </div>
      </van-tab>
    </van-tabs>

    <button class="create-button" @click="handleCreateArticle">创建文章</button>
  </div>
</template>

<script>
import axios from 'axios';
import {Popup, Button, showToast} from 'vant';
import {get, post} from "../../util/request.js";

export default {
  components: {
    [Popup.name]: Popup,
    [Button.name]: Button,
  },
  data() {
    return {
      activeTab: 'all',
      list0: [],
      searchKeyword: '',
      activeIndex: null,
      detailVisible: false,
      selectedArticle: {},
    };
  },
  async created() {
    await this.fetchUserDataForArticles(await this.onTabChange(this.activeTab));
  },
  methods: {
    async onTabChange(tab) {
      try {
        let url;
        switch (tab) {
          case 'all':
            url = 'study/article/all';
            break;
          case 'bkjy':
            url = 'study/article/bkjy';
            break;
          case 'alfx':
            url = 'study/article/alfx';
            break;
          case 'kt':
            url = 'study/article/kt';
            break;
          case 'jzs':
            url = 'study/article/jzs';
            break;
          case 'js':
            url = 'study/article/js';
            break;
          default:
            url = 'study/article/bkjy';
        }

        const response = await get(url);
        this.list0 = response.data.data.map(item => ({
          ...item,
          createdAt: item.createdAt || '',
          views: item.views || 0,
          commentsCount: item.commentsCount || 0,
        }));
        // 直接在此处调用 fetchUserDataForArticles，传入刚获取的文章列表
        await this.fetchUserDataForArticles(this.list0);
      } catch (error) {
      }
    },

    async fetchUserDataForArticles(articles) {

      for (let i = 0; i < articles.length; i++) {
        try {
          get(`user/user/selectUser/${article.userId}`).then(userDataResponse => {
          //const userDataResponse = await axios.get(`http://localhost:9090/user/user/selectUser?userId=${article.userId}`);
          if (userDataResponse.data.code === 0) {
            const userData = userDataResponse.data.value; // 修改这里
            article.authorUsername = userData.username; // 修改这里
            article.authorImageUrl = userData.imageUrl; // 修改这里
          } else {
            console.error(`Failed to fetch user data for userId: ${article.userId}`, userDataResponse.data.message);
          }}).catch(function () {
            showToast("查询全部异常")
          });

          const userDataResponse = await get(`user/user/selectUser/${articles[i].userId}`);
          if (userDataResponse.code === 0) {
            const userData = userDataResponse.data;
            articles[i].authorUsername = userData.username;
            articles[i].authorImageUrl = userData.imageUrl;
          } else {
          }
        } catch (error) {
        }
      }
      // 注意：这里不需要再次给 this.list0 赋值，因为在 onTabChange 内部已经赋值过了
    },
    handleCreateArticle() {
      // 这里可以添加一些逻辑，比如跳转到创建文章的页面
      this.$router.push('/createArticle');
    },
    async handleSearch() {
      console.log('搜索关键词:', this.searchKeyword);

      try {
        const response = await get(`study/article/search?keyword=${this.searchKeyword}`);

        // 首先映射文章数据并设置默认值
        let updatedArticles = response.data.data.map(item => ({
          ...item,
          createdAt: item.createdAt || '',
          views: item.views || 0,
          commentsCount: item.commentsCount || 0,
        }));

        // 然后调用fetchUserDataForArticles方法来获取并添加用户信息
        updatedArticles = await this.fetchUserDataForArticles(updatedArticles);

        // 最后，将更新了用户信息的文章列表赋值给list0
        this.list0 = updatedArticles;
      } catch (error) {
        console.error('搜索请求异常：', error);
      }
    }
  },

};
</script>

<style scoped>
.create-button {
  position: fixed;
  bottom: 100px; /* 距离顶部20px */
  right: 20px; /* 距离右侧20px */
  z-index: 999; /* 确保按钮位于最顶层 */
  background-color: #007bff; /* 按钮背景色 */
  color: #fff; /* 按钮文字颜色 */
  padding: 10px 20px; /* 按钮内边距 */
  border: none; /* 取消边框 */
  border-radius: 5px; /* 按钮圆角 */
  cursor: pointer; /* 鼠标样式为手型 */
}
/* 添加到 .home 的外部样式表或 <style> 标签 */
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f7f7fa;
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
}
.header-title {
  color: #333;
  font-size: 18px;
}

.search-form {
  position: relative;
  margin-left: 10px;
}

.search-input {
  width: 200px;
  padding: 10px;
  border: none;
  border-radius: 4px;
  outline: none;
}

.search-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 10px;
  background-color: transparent;
  border: none;
  cursor: pointer;
  font-size: 16px;
  color: #409eff;
}

.card__avatar {
  width: 50px; /* 根据需要设置合适的宽度和高度 */
  height: 50px;
  border-radius: 50%; /* 将边框半径设置为50%，即变为圆形 */
  object-fit: cover; /* 确保图片铺满整个圆形区域 */
}

.card-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
}

.card-content {
  padding-top: 16px;
}

.image {
  width: 100%;
  height: auto;
}


</style>